package com.birdboot.core;

import com.birdboot.annotations.Controller;
import com.birdboot.annotations.RequestMapping;

import java.io.File;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 该类用于维护请求路径与对应的Controller的处理方法
 */
public class HandlerMapping {
    private static Map<String, Method> mapping = new HashMap<>();

    static{
        initMapping();
    }

    /**
     *  扫描controller包初始化mapping这个Map
     */
    private static void initMapping(){
        try {
            File baseDir = new File(
                HandlerMapping.class.getClassLoader().getResource(".").toURI()
            );
            File dir = new File(baseDir,"com/birdboot/controller");

            File[] subs = dir.listFiles(f->f.getName().endsWith(".class"));
            for(File sub : subs){
                String fileName = sub.getName();
                String className = fileName.substring(0,fileName.indexOf("."));
                Class cls = Class.forName("com.birdboot.controller."+className);
                //判断该类是否被注解@Controller标注
                if(cls.isAnnotationPresent(Controller.class)){
                    //获取该类中所有的方法
                    Method[] methods = cls.getDeclaredMethods();
                    for(Method method : methods){
                        //判断该方法是否被注解@RequestMapping标注
                        if(method.isAnnotationPresent(RequestMapping.class)){
                            //获取注解参数
                            RequestMapping rm = method.getAnnotation(RequestMapping.class);
                            String value = rm.value();
                            //将注解参数作为key，将该方法对象作为value存入mapping
                            mapping.put(value,method);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据请求路径获取对应的处理方法
     * @param path
     * @return
     */
    public static Method getMethod(String path){
        return mapping.get(path);
    }

    public static void main(String[] args) {
        System.out.println(mapping);
    }
}






